package guda.house.web.action.api;

import guda.grape.util.RequestUtil;
import guda.house.biz.beans.vo.JsonResult;
import guda.house.dal.dao.SuiteDAO;
import guda.house.dal.dao.SuiteOutUserRelDAO;
import guda.house.dal.dataobject.SuiteDO;
import guda.house.dal.dataobject.SuiteOutUserRelDO;
import guda.house.web.helper.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by well on 16/3/4.
 */
@Controller
@RequestMapping(value = "api/user")
public class ApiOutUserAction {

    @Autowired
    private SuiteOutUserRelDAO suiteOutUserRelDAO;
    @Autowired
    private SuiteDAO suiteDAO;

    @RequestMapping(value = "bindUser.htm")
    public void bindUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        long suiteId = RequestUtil.getLong(request, "suiteId");
        String outUserId = request.getParameter("outUserId");
        JsonResult result = JsonResult.getInstance();
        if (suiteId == 0 || StringUtils.isEmpty(outUserId)) {
            result.setErrMsg("缺少参数!");
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }
        SuiteDO suiteById = suiteDAO.getSuiteById(suiteId);
        if(suiteById == null){
            result.setErrMsg("房号不存在!");
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }

        List<SuiteOutUserRelDO> byOutUserId = suiteOutUserRelDAO.getByOutUserId(outUserId);
        if(byOutUserId.size()>0){
            result.setErrMsg("该用户已经绑定过房号!");
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }
        SuiteOutUserRelDO suiteOutUserRelDO = new SuiteOutUserRelDO();
        suiteOutUserRelDO.setSuiteId(suiteId);
        suiteOutUserRelDO.setOutUserId(outUserId);
        suiteOutUserRelDAO.insert(suiteOutUserRelDO);

        ResponseHelper.ajaxReturn(result.getMap(), response);

    }

    @RequestMapping(value = "unBindUser.htm")
    public void unBindUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        long suiteId = RequestUtil.getLong(request, "suiteId");
        String outUserId = request.getParameter("outUserId");
        JsonResult result = JsonResult.getInstance();
        if (suiteId == 0 || StringUtils.isEmpty(outUserId)) {
            result.setErrMsg("缺少参数!");
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }
        suiteOutUserRelDAO.delSuiteOutUser(suiteId, outUserId);
        ResponseHelper.ajaxReturn(result.getMap(), response);

    }

}
